//
//  BrowsePlantViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 29/03/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "BrowsePlantViewController.h"
#import "Plant.h"
#import "PlantDetailTableViewController.h"
#import "UILabel+TextFont.h"

@interface BrowsePlantViewController()

@property (nonatomic, strong)UIImageView *rightArrowImageView;
@property (nonatomic, strong)UIImageView *leftArrowImageView;
@property (nonatomic, strong)UIImageView *rightCompanionArrowImageView;
@property (nonatomic, strong)UIImageView *leftCompanionArrowImageView;

- (void)loadPrimaryScrollViewWithPlantIndex:(NSInteger)plantIndex isCurrentPlant:(BOOL)currentPlant;
- (IBAction)companionPlantTapped:(UITapGestureRecognizer *)sender;
- (void) addOrRemoveArrowsFromScrollView:(UIScrollView *)scrollView;
- (void) addCompanionLabelToView:(int)screenCount;
@end


@implementation BrowsePlantViewController
@synthesize primaryScrollView = _primaryScrollView;
@synthesize companionScrollView = _companionScrollView;
@synthesize primaryPlant = _primaryPlant;
@synthesize plantList = _plantList;
@synthesize viewList = _viewList;
@synthesize indexOfPlant = _indexOfPlant;
@synthesize primaryPlantView = _primaryPlantView;
@synthesize companionPlantView = _companionPlantView;
@synthesize rightArrowImageView = _rightArrowImageView;
@synthesize leftArrowImageView = _leftArrowImageView;
@synthesize rightCompanionArrowImageView = _rightCompanionArrowImageView;
@synthesize leftCompanionArrowImageView = _leftCompanionArrowImageView;


#pragma mark - ScrollView Setup

/*Set the dimensions and attributes of the primary plant scrollview*/
-(void)setupPrimaryScrollArea
{
    //Configure the scrollView
    self.primaryScrollView.pagingEnabled = YES;
    self.primaryScrollView.contentSize = CGSizeMake(self.primaryScrollView.frame.size.width * [self.plantList count], 109);
    self.primaryScrollView.showsHorizontalScrollIndicator = NO;
    self.primaryScrollView.showsVerticalScrollIndicator = NO;
    self.primaryScrollView.scrollsToTop = NO;
    self.primaryScrollView.delegate = self;
    [self addOrRemoveArrowsFromScrollView:self.primaryScrollView];
}

/*Set the dimensions and attributes of the companion plant scrollview*/
-(void)setupCompanionScrollArea
{
    //Remove any existing plants that are in the companion scrollView
    for (UIView *companionPlantView in self.companionScrollView.subviews) {
        [companionPlantView removeFromSuperview];
    }

    self.companionScrollView.pagingEnabled = YES;
    //Get the number of screens. e.g. if we have 5 companions that means 5/3 = 1.66 then rounding up will give us 2 screens. That means
    //that we have 3 companions on screen 1 and 2 companions on screen 2. Boo ya!
    
    CGFloat numberOfScreens = ceil([self.primaryPlant.companions count]/3.0);
    self.companionScrollView.contentSize = CGSizeMake(self.companionScrollView.frame.size.width * numberOfScreens, 257);
    self.companionScrollView.showsHorizontalScrollIndicator = NO;
    self.companionScrollView.showsVerticalScrollIndicator = NO;
    self.companionScrollView.scrollsToTop = NO;
    self.companionScrollView.delegate = self;
    [self addOrRemoveArrowsFromScrollView:self.companionScrollView];
    [self addCompanionLabelToView:0];

}

/*Animate a plant image as it gets displayed*/
-(void)scaleImageIntoView:(UIImageView *)imageView withDelay:(CGFloat)delay
{
    imageView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [UIView animateWithDuration:0.15 delay:delay options:UIViewAnimationOptionCurveEaseOut animations:^{
        // animate it to the identity transform (110% scale)
        imageView.transform = CGAffineTransformMakeScale(1.1, 1.1);
        
    } completion:^(BOOL finished){
        //Give it the bounce effect. Scale it back to its original size
        [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            // animate it to the identity transform (100% scale)
            imageView.transform = CGAffineTransformIdentity;
            
        } completion:^(BOOL finished){ }];
    }];
}

/*Add a companion plant to the companion scrollview at a specific point*/
-(void)addCompanionPlantTViewToScrollViewAtOrigin:(CGPoint)origin withPlant:(Plant *)companionPlant atIndex:(int)plantIndex
{
    //Load the NIB for the companion plant view
    [[NSBundle mainBundle] loadNibNamed:@"CompanionPlantView" owner:self options:nil];
    
    CGRect frame = CGRectMake(origin.x, origin.y, 80, 60);
    self.companionPlantView.frame = frame;

    if(self.companionPlantView.superview == nil){
        [self.companionScrollView addSubview:self.companionPlantView];
    }
    
    //Set the properties of the comapanion plant NIB.
    
    UIImageView *plantImageView = (UIImageView *)[self.companionPlantView viewWithTag:1];
    [self scaleImageIntoView:plantImageView withDelay:0.1];
    
    plantImageView.contentMode = UIViewContentModeScaleAspectFit;
    plantImageView.image = [UIImage imageNamed:[companionPlant.name stringByAppendingString:@"_S"]];
    
    plantImageView.tag = plantIndex + 32;
    
    //A a ggesture recognizer for selecting a plant
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(companionPlantTapped:)];
    [plantImageView addGestureRecognizer:tapGesture];
    
    UILabel *plantNameLabel = (UILabel *)[self.companionPlantView viewWithTag:2];
    plantNameLabel.text = companionPlant.name;
    [plantNameLabel setSketchBlockFontWithLightGreeColor];

}

/*Add the companion plant label to each page on the companion scrollview*/
- (void)addCompanionLabelToView:(int)screenCount
{
    UILabel *companionLabel = [[UILabel alloc] init];
    companionLabel.text = @"Companions";   
    [companionLabel setFont:[UIFont fontWithName:@"Sketch Block" size:20]];
    companionLabel.textColor = [UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1];
    
    //screen width - label width divided by 2 = start position of the label on screen. EXAMPLE: ((320 - 97) / 2) + 320 * 1
    int startPositionOfLabel = ((self.companionScrollView.frame.size.width - 130) / 2);
    //Add the startPositionOfLabel to the screen width. Multiply by the screen count to put it on the correct screen.
    int x = startPositionOfLabel + self.companionScrollView.frame.size.width * screenCount;
        companionLabel.frame = CGRectMake(x, 7, 200, 26);
    companionLabel.backgroundColor = [UIColor clearColor];

    [self.companionScrollView addSubview:companionLabel];
    
}

/*Load the companion plants for the current primary plant and then add it to the companion scrollview*/
-(void)loadCompanionPlants
{
    //Build up an arry of our points.
    NSMutableArray *points = [[NSMutableArray alloc] 
                              initWithObjects:[NSValue valueWithCGPoint:CGPointMake(30, 30)], [NSValue valueWithCGPoint:CGPointMake(190, 30)], [NSValue valueWithCGPoint:CGPointMake(120, 150)], nil];
    NSArray *companions = [self.primaryPlant.companions allObjects];
    int screenCount = 0;
    int pointCount = 0;
    //Iterate over the list of companions and add them to the scrollview. For every 3rd plant we recalculate the screencount and the CGPoints for each plant on screen
    for(int i = 0; i < [companions count]; i++){
        Plant *plant = [companions objectAtIndex:i];
        [self addCompanionPlantTViewToScrollViewAtOrigin:[[points objectAtIndex:pointCount] CGPointValue] withPlant:plant atIndex:i];
        //NSLog(@"Added %@ on screen %d at points %@", plant.name, screenCount, [points objectAtIndex:pointCount]);
        pointCount++;
        //Increment the screenCount for every third companion plant
        if(fmod(i + 1, 3.0) == 0){
            screenCount++;
            for (int x = 0; x < [points count]; x++) {
                CGPoint point = [[points objectAtIndex:x] CGPointValue];
                point.x = point.x + (self.companionScrollView.frame.size.width);
                [points replaceObjectAtIndex:x withObject:[NSValue valueWithCGPoint:point]];
            }
            //Reset the point count to zero. We are starting again with new points.
            pointCount = 0;
           
            [self addCompanionLabelToView:screenCount];
        }
    } 
}

/*When the primary plant is selected we reconfigure the companion scrollview and load that plants companions*/
-(void)setPrimaryPlant:(Plant *)primaryPlant
{
    if(primaryPlant != _primaryPlant){
        _primaryPlant = primaryPlant;
        [self setupCompanionScrollArea];
        [self loadCompanionPlants];
    }
}

/**/
- (void)loadPrimaryScrollViewWithPlantIndex:(NSInteger)plantIndex isCurrentPlant:(BOOL)currentPlant
{
    //Don't load a page if we go beyond the bounds of the plant list.
    if(plantIndex < 0 || plantIndex >= [self.plantList count]){
        return;
    }
    
    //Get the plant View
    UIView *plantView = [self.viewList objectAtIndex:plantIndex];
    //Grab the plant object
    Plant *plant = [self.plantList objectAtIndex:plantIndex];

    //We are loading the current plant on screen so set this as the primary plant
    if(currentPlant == YES){
        self.primaryPlant = plant;
    }
    //If the plant view is nil then we need to load up that view from the PrimaryPlantView NIB.
    if ((NSNull *)plantView == [NSNull null])
    {
        [[NSBundle mainBundle] loadNibNamed:@"PrimaryPlantView" owner:self options:nil];
        plantView = self.primaryPlantView;
        [self.viewList replaceObjectAtIndex:plantIndex withObject:plantView];
    }
    
    // add the view to the scroll view
    if (self.primaryPlantView.superview == nil)
    {
        CGRect frame = self.primaryScrollView.frame;
        //Subtract the width of the image and divide it by two to get the start point of the image.
        int x = ((frame.size.width) - 190)/2;
        //For subequent screens add the width of the scrollview frame multiplied by the plant index
        if(plantIndex > 0){
            x = x + (frame.size.width * (plantIndex));
        }
        frame.origin.x = x;
        frame.origin.y = -10;
        //Width of the frame that will hold the image
        frame.size.width = 190;
        frame.size.height = 100;
        plantView.frame = frame;

        [self.primaryScrollView addSubview:plantView];
        
        UIImageView *plantImageView = (UIImageView *)[plantView viewWithTag:1];
        [self scaleImageIntoView:plantImageView withDelay:0.0];
        
        plantImageView.contentMode = UIViewContentModeScaleAspectFit;
        plantImageView.image = [UIImage imageNamed:[plant.name stringByAppendingString:@"_M"]];
        
        UILabel *plantNameLabel = (UILabel *)[plantView viewWithTag:2];
        plantNameLabel.text = plant.name;
        [plantNameLabel setSketchBlockFontWithLightGreeColor];

        //If we are on the current primary plant then scroll to it.
        if(currentPlant == YES){
            frame.origin.x = (frame.origin.x + 65);
            [self.primaryScrollView scrollRectToVisible:frame animated:NO];
        }
        
    }
}

/*Calcualte whether we should add or remove next and previous arrows from the companion and primary scrollviews*/
-(void) addOrRemoveArrowsFromScrollView:(UIScrollView *)scrollView
{
    //Set up some imageView placeholders
    UIImageView *tempRightArrow;
    UIImageView *tempLeftArrow;
    
    //Assign the correct imageView objects. Either from the primary or companion scrollView
    if([scrollView isEqual:self.primaryScrollView]) {
        tempRightArrow = rightArrowImageView;
        tempLeftArrow = leftArrowImageView;
        
    } else if([scrollView isEqual:self.companionScrollView]) {
        tempRightArrow = rightCompanionArrowImageView;
        tempLeftArrow = leftCompanionArrowImageView;
    }
    
    if(((scrollView.contentOffset.x + 320) == scrollView.contentSize.width) || scrollView.contentSize.width == 0){
        //we have reached the end.
        [tempRightArrow removeFromSuperview];
    }else{
        if(![tempRightArrow isDescendantOfView:self.view]){
            [self.view addSubview:tempRightArrow];
        }
    }
    if(scrollView.contentOffset.x == 0){
        [tempLeftArrow removeFromSuperview];
    }else{
        if(![tempLeftArrow isDescendantOfView:self.view]){
            [self.view addSubview:tempLeftArrow];
        }
    }
}

#pragma mark - Scrolling Delegates

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if([scrollView isEqual:self.primaryScrollView]){
        CGFloat pageWidth = scrollView.frame.size.width;
        int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        
        //Load primary plants for page -1, 0 and 1
        [self loadPrimaryScrollViewWithPlantIndex:(page - 1) isCurrentPlant:NO];
        [self loadPrimaryScrollViewWithPlantIndex:page isCurrentPlant:YES];
        [self loadPrimaryScrollViewWithPlantIndex:(page + 1) isCurrentPlant:NO];
        
        [self addOrRemoveArrowsFromScrollView:scrollView];
        
    }else if([scrollView isEqual:self.companionScrollView]){
        [self addOrRemoveArrowsFromScrollView:scrollView];

    }
}



#pragma mark - Touch Events and Segues

- (IBAction)companionPlantTapped:(UITapGestureRecognizer *)sender
{
    UIImageView *tappedImage = (UIImageView *)sender.view;
    NSArray *companions = [self.primaryPlant.companions allObjects];
    Plant *tappedPlant = [companions objectAtIndex:(tappedImage.tag - 32)];
    
    [self performSegueWithIdentifier:@"viewPlantDetail" sender:tappedPlant];
}

- (IBAction)plantTapped:(UITapGestureRecognizer *)sender 
{
    [self performSegueWithIdentifier:@"viewPlantDetail" sender:sender];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"viewPlantDetail"]) {
        if([sender isKindOfClass:([Plant class])]){
            [segue.destinationViewController setPlant:sender];
        }else {
            
            [segue.destinationViewController setPlant:self.primaryPlant];
        }
        
    }
}



#pragma mark - View lifecycle


-(void)viewDidAppear:(BOOL)animated
{
   
    // views are created lazily
    // in the meantime, load the array with placeholders which will be replaced on demand
    NSMutableArray *views = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < [self.plantList count]; i++)
    {
		[views addObject:[NSNull null]];
    }
    self.viewList = views;
    
    
    //If the primary plant has been set, then get its index in the list of plants.
    //This only executes when coming back from the plant detail screen.
    if(self.primaryPlant){
        self.indexOfPlant = [self.plantList indexOfObject:self.primaryPlant];
    }

    [self loadPrimaryScrollViewWithPlantIndex:self.indexOfPlant isCurrentPlant:YES];
    
}



-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.viewList removeAllObjects];
    
    for (UIView *plantViews in self.primaryScrollView.subviews) {
        [plantViews removeFromSuperview];
    }
}

-(void)setupScrollArrows
{
    //Primary ScrollView
    rightArrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"browse_right.png"]];
    rightArrowImageView.frame = CGRectMake(255, 295, 50, 37);
    leftArrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"browse_left.png"]];
    leftArrowImageView.frame = CGRectMake(5, 295, 40, 37);
    
    //Companion ScrollView
    rightCompanionArrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"companion_right.png"]];
    rightCompanionArrowImageView.frame = CGRectMake(255, 125, 40, 27);
    leftCompanionArrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"companion_left.png"]];
    leftCompanionArrowImageView.frame = CGRectMake(5, 125, 30, 27);
}

-(void)viewDidLoad
{

    //Set the background image of the vieway
    self.primaryScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"browse_selected_bg.png"]];
    self.companionScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"browse_companions_bg.png"]];
    [self setupScrollArrows];
    [self setupPrimaryScrollArea];
}





- (void)viewDidUnload
{
    [self setPrimaryScrollView:nil];
    [self setCompanionScrollView:nil];
    [self setPrimaryPlantView:nil];
    [self setCompanionPlantView:nil];
    [super viewDidUnload];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


@end
